package com.dacd.soundanalysis.activity

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.dacd.soundanalysis.R
import com.dacd.soundanalysis.filehelper.FileConstants
import com.dacd.soundanalysis.sharepreferences.ShareConstants
import com.dacd.soundanalysis.sharepreferences.SharePreHelper
import com.dacd.soundanalysis.soundhelper.RecordState
import com.dacd.soundanalysis.thread.LearnRecThread
import com.dacd.soundanalysis.thread.ListenThread
import com.dacd.tcgandroid.dialog.DialogFactory
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.lang.ref.WeakReference


class MainActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        private class WithoutLeakHandler(activity: MainActivity) : Handler() {
            private var mActivity: WeakReference<MainActivity> = WeakReference(activity)

            override fun handleMessage(msg: Message?) {
                val activity = mActivity.get()
                when (msg!!.what) {
                    0 -> {
                        activity!!.am_result_tv.setText(R.string.ma_compare_sucess)
                    }
                    1 -> {
                        activity!!.am_start_record_tv.setText(R.string.ma_start_learn_first_key)
                    }
                    2 -> {
                        activity!!.am_start_record_tv.setText(R.string.ma_start_compare_first_key)
                    }
                    3 -> {//存入次数刷新
                        activity!!.saveTimes = msg.arg1
                        SharePreHelper.setSP(activity, ShareConstants.SAVE_TIMES, activity.saveTimes)
                        activity.am_save_times_tv.text = String.format(
                            activity.getString(R.string.ma_save_times),
                            (if (activity.saveTimes == -1) 0 else activity.saveTimes).toString()
                        )
                        activity.am_start_record_tv.text = ""
                    }
                    4 -> {
                        activity!!.am_progress_layout.visibility = View.VISIBLE
                        activity.handler.sendEmptyMessageDelayed(5 , 2000)
                    }
                    5 -> {
                        activity!!.am_progress_layout.visibility = View.GONE
                    }
                }
            }
        }
    }

    private var handler: Handler = WithoutLeakHandler(this)
    private var learnRecThread: LearnRecThread? = null
    private var listenThread: ListenThread? = null
    private var saveTimes:Int = 0//学习模板的次数
    private var nowState: RecordState = RecordState.NONE//记录当前状态

    /**
     * 声音请求权限信息
     */
    private val PERMISSION_AUDIORECORD = 2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
    }

    private fun initView() {
        am_progress_layout.visibility = View.GONE
        btn1.setOnClickListener(this)
        btn2.setOnClickListener(this)
        btn3.setOnClickListener(this)
        btn4.setOnClickListener(this)
        btn5.setOnClickListener(this)
        btn6.setOnClickListener(this)
        saveTimes = SharePreHelper.getSPInt(this, ShareConstants.SAVE_TIMES)!!
        am_save_times_tv.text = String.format(
            getString(R.string.ma_save_times),
            (if (saveTimes == -1) 0 else saveTimes).toString()
        )
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            btn1.id -> {//开始采集素材加权限申请
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.RECORD_AUDIO
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //如果应用之前请求过此权限但用户拒绝的请求 ,此方法返回true
                    if (ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.RECORD_AUDIO
                        )
                    ) {
                        //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限
                    } else {
                        ActivityCompat.requestPermissions(
                            this,
                            arrayOf(Manifest.permission.RECORD_AUDIO),
                            PERMISSION_AUDIORECORD
                        )
                    }

                } else {
                    if(saveTimes > 4) {
                        DialogFactory.showDismissDialog(this, getString(R.string.ma_record_times_limite), R.string.en_ok)
                        return
                    }
                    if(verifyRecordControl()) {
                        startLearn()
                        nowState = RecordState.LEARN
                        am_notice_tv.text =
                            String.format(getString(R.string.ma_history_control), getString(R.string.ma_start_learn))
                        show2SecProgress()
                    }
                }
            }
            btn2.id -> {//停止采集素材
                if(nowState != RecordState.LEARN) {//如果不在录制素材的状态
                    DialogFactory.showDismissDialog(this, getString(R.string.ma_not_start_learn), R.string.en_ok)
                    return
                }
                learnRecThread!!.stopRecord()
                saveTimes = SharePreHelper.getSPInt(this, ShareConstants.SAVE_TIMES)!!
                am_save_times_tv.text = String.format(
                    getString(R.string.ma_save_times),
                    (if (saveTimes == -1) 0 else saveTimes).toString()
                )
                am_notice_tv.text = String.format(getString(R.string.ma_history_control), getString(R.string.ma_stop_learn))
                nowState = RecordState.NONE
                show2SecProgress()
            }
            btn3.id -> {//开始录制进行匹配
                if (saveTimes < 5) {
                    DialogFactory.showDismissDialog(this, getString(R.string.ma_not_enough_data), R.string.en_ok)
                    return
                }
                if(verifyRecordControl()) {
                    startRecord()
                    nowState = RecordState.RECORD
                    am_notice_tv.text =
                        String.format(getString(R.string.ma_history_control), getString(R.string.ma_start_record))
                }
                show2SecProgress()
            }
            btn4.id -> {//停止匹配
                if(nowState != RecordState.RECORD) {//如果不在匹配的状态
                    DialogFactory.showDismissDialog(this, getString(R.string.ma_not_start_record), R.string.en_ok)
                    return
                }
                listenThread!!.stopRecord()
                am_notice_tv.text =
                    String.format(getString(R.string.ma_history_control), getString(R.string.ma_stop_record))
                nowState = RecordState.NONE
                show2SecProgress()
            }
            btn5.id -> {
                am_result_tv.text = ""
                am_start_record_tv.text = ""
            }
            btn6.id -> {//清除所有素材
                if(verifyRecordControl()) {
                    val recordDir =
                        File(cacheDir.absolutePath + FileConstants.RECORD_FILE_DIR)//存放音频的文件夹
                    if (recordDir.exists()) {
                        recordDir.deleteRecursively()
                    }
                    am_notice_tv.text =
                        String.format(getString(R.string.ma_history_control), getString(R.string.ma_clear_learn_data))
                    saveTimes = 0
                    SharePreHelper.setSP(this, ShareConstants.SAVE_TIMES, 0)
                    am_save_times_tv.text = String.format(
                        getString(R.string.ma_save_times),
                        (if (saveTimes == -1) 0 else saveTimes).toString()
                    )
                }
            }
        }
    }

    private fun startLearn() {
        learnRecThread = LearnRecThread(this, handler)
        val initSuccess = learnRecThread!!.initAudioLearnThread()
        learnRecThread!!.start()
    }

    private fun startRecord() {
        listenThread = ListenThread(this, handler)
        listenThread!!.initAudioLearnThread()
        listenThread!!.start()
    }

    private fun show2SecProgress() {
        handler.sendEmptyMessage(4)
    }

    /**
     * 验证是否能够点击录制按钮
     */
    private fun verifyRecordControl(): Boolean {
        if (nowState == RecordState.LEARN) {//正在学习中
            DialogFactory.showDismissDialog(this, getString(R.string.ma_already_start_learn), R.string.en_ok)
            return false
        }
        if (nowState == RecordState.RECORD) {
            DialogFactory.showDismissDialog(this, getString(R.string.ma_already_record_learn), R.string.en_ok)
            return false
        }
        return true
    }
}
